var app = getApp();
var globalData = app.globalData;
var _utils = require('../../lib/utils.js');

Page({
  data: {
    avatarUrl: globalData.avatarUrl,
    nickName: globalData.nickname,
    auth: -1,
    daysStyle: [],
    todayEmotion: '',
    activeEmotion: 'serene',
    emotions: ['serene', 'hehe', 'ecstatic', 'sad', 'terrified'],
    colors: {
      serene: '#64d9fe',
      hehe: '#d3fc1e',
      ecstatic: '#f7dc0e',
      sad: '#ec238a',
      terrified: '#ee1aea'
    }
  },

  goBack() {
    wx.navigateBack();
  },

  onShareAppMessage() {
    return {
      title: '我发现一个好玩的小程序，分享给你看看！',
      path: '/pages/diary/index'
    };
  },

  onLoad: function onLoad(options) {
    var that = this;
    this.setData({
      curMonth: (0, _utils.dateFormat)(new Date(), 'yyyy-MM')
    });

    // 判断是否登录有权限
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          that.getUserInfo()
        } else {
          that.setData({ auth: 0 });
        }
      }
    });
  },

  // 登录验证授权
  getUserInfo() {
    var that = this;
    // 如果不存在全局的数据，就获取
    if (!globalData.nickname || globalData.avatarUrl) {
      wx.getUserInfo({
        success(res) {
          let { nickName, avatarUrl } = res.userInfo
          that.setData({
            nickName,
            avatarUrl
          });
          globalData.nickname = nickName
          globalData.avatarUrl = avatarUrl
        }
      });
    }
    var storageOpenid = wx.getStorageSync('openid');
    function callback() {
      that.setData({
        auth: 1,
        openid: storageOpenid
      });
      var now = new Date();
      var year = now.getFullYear();
      var month = now.getMonth() + 1;
      var data = globalData['diary-' + year + '-' + month] || [];
      if (data && data.length) {
        // 当前月份，存在缓存
        that._setDayData(data, year, month);
      } else {
        that.setCalendarColor();
      }
    }
    if (storageOpenid) {
      callback();
    } else {
      wx.login({
        success(res) {
          console.log("success -> res", res)
          /* wx.cloud.callFunction({
            name: 'login',
            data: { code: res.code },
          }).then(res => {
            let { openid, session_key } = res.result
            if (openid && session_key) {
              wx.setStorage({
                key: 'openid',
                data: openid
              });
              storageOpenid = openid;
              callback()
            } else {
              //授权失败，显示登录按钮
              that.setData({ auth: 0 })
            }
          }).catch(e => {
          }) */

          wx.request({
            url: 'http://localhost:3000/login',
            data: { code: res.code },
            success(res) {
              let { openid, session_key } = res
              if (openid && session_key) {
                wx.setStorage({
                  key: 'openid',
                  data: openid
                });
                storageOpenid = openid;
                callback()
              } else {
                //授权失败，显示登录按钮
                that.setData({ auth: 0 })
              }
            },
          })
        }
      });
    }
  },

  _setDayData(data, year, month) {
    var colors = this.data.colors;
    var styles = [];
    var now = new Date();
    var today = (0, _utils.dateFormat)(now);
    var todayEmotion = '';
    data.forEach(function (v) {
      var ts = v.tsModified;
      var date = new Date(ts);
      var day = date.getDate();
      if (today === (0, _utils.dateFormat)(date)) {
        todayEmotion = v.emotion || '';
      }
      styles.push({
        month: 'current',
        day: day,
        color: 'black',
        background: colors[v.emotion]
      });
    });
    // console.log(styles, today)
    this.setData({
      lastMonth: year + '-' + ('00' + month).slice(-2),
      showPublish: true,
      todayEmotion: todayEmotion,
      daysStyle: styles
    });
  },

  setCalendarColor(year, month) {
    console.log(1)
    var that = this;
    let openid = that.data.openid
    year = year || new Date().getFullYear();
    month = month || new Date().getMonth() + 1;
    wx.cloud.callFunction({
      name: 'getEmotion',
      data: { openid, year, month },
    }).then(res => {
      var data = res.result.data || [];
      globalData['diary-' + year + '-' + month] = data
      that._setDayData(data, year, month);
    }).catch(e => {
      wx.showToast({
        title: '加载已签数据失败，请稍后再试',
        icon: 'none',
        duration: 3000
      });
    })
  },

  dateChange: function dateChange(e) {
    var _e$detail = e.detail,
      currentYear = _e$detail.currentYear,
      currentMonth = _e$detail.currentMonth;

    this.setData({
      daysStyle: []
    });
    this.setCalendarColor(currentYear, currentMonth);
  },

  checkedColor: function checkedColor(e) {
    let activeEmotion = e.currentTarget.dataset.emotion
    this.setData({
      activeEmotion
    });
  },

  submitEmotion() {
    let that = this
    let { openid, activeEmotion, colors } = this.data
    var db = wx.cloud.database()
    db.collection('diary').add({
      data: {
        openid: openid,
        emotion: activeEmotion,
        tsModified: Date.now()
      }
    }).then(res => {
      if (res._id) {
        var styles = that.data.daysStyle || [];
        var day = new Date().getDate();
        styles.push({
          month: 'current',
          day: day,
          color: 'black',
          background: colors[activeEmotion]
        });
        that.setData({
          daysStyle: styles,
          todayEmotion: activeEmotion
        });
        // 将今天数据更新到globalData
        var now = new Date();
        var year = now.getFullYear();
        var month = now.getMonth() + 1;
        var data = globalData['diary-' + year + '-' + month] || [];
        if (data.length) {
          data.push({
            openid: openid,
            emotion: activeEmotion,
            tsModified: Date.now()
          });
        }
      }
    }).catch(e => {
      wx.showToast({
        title: '签到失败，请稍后再试',
        icon: 'none',
        duration: 3000
      });
    })
  },
})